﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiGeSIB.Data.Security;
using SiGeSIB.Data.Common;
using System.Xml;
using System.IO;
using System.Data.SqlClient;

namespace SiGeSIB.Data.Security
{
	public class ConfigurationManager : IContentsSerializable
	{
		private ConfigurationManager()
		{
            Connections = new ConnectionSchemaCollection();
            
            // Se o diretório já existe, não faz nada e não lança exceção
			Directory.CreateDirectory(ApplicationDataPath);

			string configPath = Path.Combine(ApplicationDataPath, CONNECTIONS_FILE_NAME);

			if (File.Exists(configPath))
			{
				try
				{
					XmlDocument docConfig = new XmlDocument();
					docConfig.Load(configPath);
					this.Deserialize(docConfig[XmlElementName]);
				}
				catch
				{
					// Não faz nada, simplesmente não conseguiu ler o xml de conexões
				}
			}
		}

		#region Attributes
		private static ConfigurationManager _Instance;
		private const string XML_DEFAULT_LOGIN = "DefaultLogin";
		private const string XML_CONNECTIONS = "Connections";
		private const string CONNECTIONS_FILE_NAME = "Connections.xml";

		private SqlTransaction _Tran;
		#endregion

		#region Properties
		public ConnectionSchemaCollection Connections { get; protected set; }
		public string DefaultLogin { get; set; }
		public string XmlElementName { get { return "ConfigManager"; } }
		public string ApplicationDataPath { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SiGeSIB"); } }
		public static ConfigurationManager Instance
		{
			get
			{
				if (_Instance == null)
				{
					_Instance = new ConfigurationManager();
				}
				return _Instance;
			}
		} 
		#endregion

		#region IContentsSerializable Members

		public void Serialize(XmlWriter xmlw)
		{
			xmlw.WriteStartElement(XmlElementName);

			if (Connections != null)
			{
				xmlw.WriteStartElement(XML_CONNECTIONS);
				Connections.Serialize(xmlw);
				xmlw.WriteEndElement();
			}

			if (!string.IsNullOrEmpty(DefaultLogin))
				xmlw.WriteElementString(XML_DEFAULT_LOGIN, DefaultLogin);

			xmlw.WriteEndElement();
		}

		public void Deserialize(XmlNode node)
		{
			if (node != null && node.Name == XmlElementName)
			{
                if(node[XML_CONNECTIONS] != null)
				    Connections.Deserialize(node[XML_CONNECTIONS]);
				
                if (node[XML_DEFAULT_LOGIN] != null)
					DefaultLogin = node[XML_DEFAULT_LOGIN].InnerText;
			}
		}

		#endregion

		public void SaveConnections()
		{
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Encoding = Encoding.UTF8;
			settings.Indent = true;

			using (XmlWriter xmlw = XmlWriter.Create(Path.Combine(ApplicationDataPath, CONNECTIONS_FILE_NAME), settings))
			{
				Serialize(xmlw);
			}
		}

		public int SaveSchema(ConnectionSchema schema)
		{
			int id = Connections.UpdateConnection(schema);
			SaveConnections();

			return id;
		}
		public void RemoveSchema(int id)
		{
			Connections.Remove(id);
			SaveConnections();
		}

		public SqlConnection CreateConnection()
		{
			return Connections.SelectedSchema.CreateConnection();
		}
	}
}
